from apps.system.user.dao import UserDao
from apps.system.rank.dao import RankDao
from apps.pay.order.countAward.verticalAward import countVerticalAward
from apps.pay.order.countAward.gradeAward import countGradeAward

def upRankHandle(order):
    print('处理升级成功之后事项', order.activity)
    _user = UserDao().findOneByObjId(order.user.id)

    userRank = _user.rank
    if userRank.grade > 0:
        print('用户级别，已经大于要调整的级别，无需修改')
    else:
        UserDao().updateRankByUserAndGrade(_user, 1)
    
    # 计算上级收益
    if _user.parent:
        # 计算直推奖
        countVerticalAward('rank', order, 'rate', 'verticalAward')  # rate money
        # 计算见点奖
        countGradeAward('rank', order, 'rate', 'gradeAward')
        # 计算团队奖
        countGradeAward('team', order, 'rate', 'teamAward')

    # 统计并更新业绩数据
    if _user.parent:
        updateVerticalPeopleNumber('add', _user.parent, 1)
        updateVerticalOrderNumber('add', _user.parent, 1)
        updateVerticalPerformance('add', _user.parent, order.realPay)
        updateTeamPeopleNumber('add', _user, 1)
        updateTeamOrderNumber('add', _user, 1)
        updateTeamPerformance('add', _user, order.realPay)

    # 检查上级考核指标，为上级升级
    if _user.parent:
        _parent = UserDao().findOneByObjId(_user.parent.id)
        _ranks = RankDao().findAll().filter(rankType='rank').order_by('-grade')
        for rank in _ranks:
            if _parent.verticalOrderNumber >= rank.verticalOrderNumber:
                if _parent.rank.grade < rank.grade:
                    UserDao().updateRankByUserAndGrade(_parent, rank.grade)
                break
    else:
        print('上级不存在')
    
    # 检查上级团队考核指标，更新上级团队级别
    if _user.parent:
        _parent = UserDao().findOneByObjId(_user.parent.id)
        while 1:
            if _parent:
                _ranks = RankDao().findAll().filter(rankType='team').order_by('-grade')
                for rank in _ranks:
                    print('用户', _parent.id, _parent.verticalOrderNumber, _parent.teamOrderNumber)
                    print('级别', rank.grade, rank.verticalPeopleNumber, rank.teamPeopleNumber)
                    if _parent.verticalOrderNumber >= rank.verticalPeopleNumber and _parent.teamOrderNumber >= rank.teamPeopleNumber:
                        if _parent.rank.grade < rank.grade:
                            print('满足条件升级', rank.grade)
                            # UserDao().updateTeamRankByUserAndGrade(_parent, rank.grade)
                        break
                _parent = _parent.parent
                print('_parent', _parent)
            else:
                print('上级不存在')
                break
    else:
        print('上级不存在')

    